//
//  YDGUIImagePickerProvider.m
//  yidiangou
//
//  Created by lifayu on 15/12/24.
//  Copyright © 2015年 Yunva. All rights reserved.
//

#import "YDGUIImagePickerProvider.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreMedia/CoreMedia.h>
#import <MediaPlayer/MediaPlayer.h>

@interface YDGUIImagePickerProvider()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    __weak id<YDGUIImagePickerProviderDelegate> _delegate;
    NSString                             *_uniqueId;
    UIImagePickerController              *_imagePicker;
}

@end



static   YDGUIImagePickerProvider      *g_UIImagePickerProvider = nil;

@implementation YDGUIImagePickerProvider

+ (instancetype)shareInstance
{
    if(!g_UIImagePickerProvider)
    {
        g_UIImagePickerProvider = [[YDGUIImagePickerProvider alloc] init];
    }
    return g_UIImagePickerProvider;
}

+(void)release
{
    g_UIImagePickerProvider = nil;
}


//打开本地相册 选择图片 返回图片  上传图片 返回url
- (void)openLocalPhotoWithDelegate:(id<YDGUIImagePickerProviderDelegate>)aDelegate UniqueId:(NSString *)uinqueId
{
    _delegate = aDelegate;
    _uniqueId = uinqueId;
    if([_delegate isKindOfClass:[UIViewController class]])
    {
        UIViewController  *viewController = (UIViewController *)_delegate;
        
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
        _imagePicker.allowsEditing = YES;
        _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [viewController presentViewController:_imagePicker animated:YES completion:nil];
    }
}

//打开相机 拍摄图片 返回图片  上传图片 返回url
- (void)openCameraPhotoWithDelegate:(id<YDGUIImagePickerProviderDelegate>)aDelegate UniqueId:(NSString *)uinqueId
{
//    if(![PBCUtilities isCameraAvailable])
//    {
//        return;
//    }
    _delegate = aDelegate;
    _uniqueId = uinqueId;
    if([_delegate isKindOfClass:[UIViewController class]])
    {
        UIViewController  *viewController = (UIViewController *)_delegate;
        
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
        _imagePicker.allowsEditing = YES;
        _imagePicker.sourceType = UIImagePickerControllerCameraDeviceFront;
        [viewController presentViewController:_imagePicker animated:YES completion:nil];
    }
}

//打开本地视频 选择视频 返回视频默认图片  转码为MP4  上传视频 返回视频url
- (void)openLocalVideoWithDelegate:(id<YDGUIImagePickerProviderDelegate>)aDelegate UniqueId:(NSString *)uinqueId
{
    _delegate = aDelegate;
    _uniqueId = uinqueId;
    if([_delegate isKindOfClass:[UIViewController class]])
    {
        UIViewController  *viewController = (UIViewController *)_delegate;
        
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
        _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _imagePicker.mediaTypes =  [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
        [viewController presentViewController:_imagePicker animated:YES completion:nil];
    }
    
}

//打开相机拍摄视频 返回视频默认图片  转码为MP4  上传视频 返回视频url
- (void)openCameraVideoWithDelegate:(id<YDGUIImagePickerProviderDelegate>)aDelegate UniqueId:(NSString *)uinqueId
{
//    if(![PBCUtilities isCameraAvailable])
//    {
//        return;
//    }
    _delegate = aDelegate;
    _uniqueId = uinqueId;
    if([_delegate isKindOfClass:[UIViewController class]])
    {
        UIViewController  *viewController = (UIViewController *)_delegate;
        
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
        _imagePicker.sourceType = UIImagePickerControllerCameraDeviceFront;
        _imagePicker.mediaTypes =  [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
        [viewController presentViewController:_imagePicker animated:YES completion:nil];
    }
}

#pragma mark -- UIImagePickerController Delegate 选择图片后的
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"%@",info);
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if([mediaType isEqualToString:(NSString *)kUTTypeImage])
    {
        UIImage *originImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        UIImage *editImage = [info objectForKey:UIImagePickerControllerEditedImage];
        NSData *imageData = UIImageJPEGRepresentation(editImage, 0.5);
        NSString *imageTempPath = [self tempJpgImagePath];
        [imageData writeToFile:imageTempPath atomically:YES];
        
        if(_delegate && [_delegate respondsToSelector:@selector(onChoosePhotoSuccessWithFilePath:OrginImage:EditImage:UniqueId:)])
        {
            [_delegate onChoosePhotoSuccessWithFilePath:imageTempPath OrginImage:originImage EditImage:editImage UniqueId:_uniqueId];
        }
        [_imagePicker dismissViewControllerAnimated:YES completion:^{
            _imagePicker = nil;
        }];
        
    }
    else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
    {
//        NSData  *fileData = [NSData dataWithContentsOfURL:[info objectForKey:UIImagePickerControllerMediaURL]];
//        CGFloat fileSize = fileData.length/1024.0/1024.0;
//        if(fileSize > 10.0)
//        {
//            [YDGUtilities showTextHUDMaintain2Seccond:@"您选择的视频超出限制大小：10M"];
//            [picker dismissViewControllerAnimated:YES completion:nil];
//            return;
//        }
        
//        DebugLog(@"视频转码完成");
//        UIImage *defaultImage = [YDGUtilities getVideoDefaultImage:[info objectForKey:UIImagePickerControllerMediaURL]];
//        if(_delegate && [_delegate respondsToSelector:@selector(onChooseVideoSuccessWithDefaultVideoImage:UniqueId:)])
//        {
//            [_delegate onChooseVideoSuccessWithDefaultVideoImage:defaultImage UniqueId:_uniqueId];
//        }
//        
//        [YDGUtilities showHUD:@"视频转码中..." andView:_imagePicker.view];
//        [self encodeVideoToMP4:[info objectForKey:UIImagePickerControllerMediaURL]];
    }
}

// 临时图片文件存放
- (NSString *)tempJpgImagePath
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *dateString = [formatter stringFromDate:[NSDate date]];
    return nil;
//    return [NSString stringWithFormat:@"%@%@.jpg",[PBCUtilities createPhotoCacheDirectory], dateString];
}

- (void)encodeVideoToMP4:(NSURL *)filePath
{
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:filePath options:nil];
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset
                                                                          presetName:AVAssetExportPresetMediumQuality];
    NSDateFormatter* formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
    NSString * _mp4Path = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]] ;
    
    
    exportSession.outputURL = [NSURL fileURLWithPath: _mp4Path];
    exportSession.shouldOptimizeForNetworkUse = YES;
    exportSession.outputFileType = AVFileTypeMPEG4;
    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        switch ([exportSession status])
        {
            case AVAssetExportSessionStatusFailed:
            {
                DebugLog(@"视频转码失败");
                break;
            }
            case AVAssetExportSessionStatusCancelled:
                DebugLog(@"视频转码取消");
                break;
            case AVAssetExportSessionStatusCompleted:
            {
                DebugLog(@"视频转码完成");
                if(_delegate && [_delegate respondsToSelector:@selector(onChooseVideoSuccessWithFilePath:UniqueId:)])
                {
                    [_delegate onChooseVideoSuccessWithFilePath:_mp4Path UniqueId:_uniqueId];
                }
                
                [_imagePicker dismissViewControllerAnimated:YES completion:^{
                    _imagePicker = nil;
                }];
            }
                break;
            default:
                break;
        }
    }];
}



@end
